package com.zelin.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;

public class JWTBaseDemo {
    @Test
    public void test01(){
        //说明：
        //1.Jwts.builder():代表jwt生成器
        //2.setId():设置生成器的id
        //3.setIssuedAt():设置加密时间
        //4.setSubject():设置主体信息
        //signWith:设置jwt的签名
        //5.compact()：得到jwt生成的字符串
        //1.得到jwtbuilder对象
        JwtBuilder jwtBuilder =
                Jwts.builder().setId("1111")
                .setIssuedAt(new Date())
                .setSubject("admin")
                .signWith(SignatureAlgorithm.HS256,"zelin");
        //1.2.得到token对象
        String token = jwtBuilder.compact();
        //1.3. 打印
        System.out.println("token:" + token);
    }
    //2. 解析制定token
    @Test
    public void test02(){
        //2.1 得到要解析的token字符串
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMTExIiwiaWF0IjoxNTg1OTE2MzA5LCJzdWIiOiJhZG1pbiJ9.Dx0AuWqTgi5xnhrrBe5ftscagomVwH72nqwTr1WpTkE";
        //2.2 定义解析token的对象
        Claims claims = Jwts.parser().setSigningKey("zelin")
                .parseClaimsJws(token).getBody();
        String id = claims.getId();
        String subject = claims.getSubject();
        Date issuedAt = claims.getIssuedAt();
        System.out.println("id:" + id);
        System.out.println("subject:" + subject);
        System.out.println("issuedAt:" + issuedAt);
    }
}
